# -*- coding: utf-8 -*-
import hashlib
import json
from datetime import datetime

import requests
from django.conf import settings

from common.bankcard import db as bank_db
from common.bankcard.model import BANK_DCT
from common.mch import handler as mch_handler
from common.mch.db import get_account
from common.recharge import db as recharge_db
from common.recharge.model import RECHARGE_ORDER_STATUS
from common.timer import TIMER_EVENT_TYPE
from common.timer.handler import submit_notify_event
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger('third')

APP_CONF = {
    'Durotar': {
        'API_KEY': 'Unionagency1.0',
        'GATEWAY': 'http://103.230.240.107:5006/api/Orders',
        'QUERY_GATEWAY': 'http://103.230.240.107:5006/api/Orders/Status',
        'INFO': '测试环境',
    },
    # 'Durotar': {
    #     'API_KEY': 'HyDra_Unionagency1.0@prod_server',
    #     'GATEWAY': 'http://103.71.51.51:5006/api/Orders',
    #     'QUERY_GATEWAY': 'http://103.71.51.51:5006/api/Orders/Status',
    #     'INFO': '正式环境',
    # },
    'loki': {
        'API_KEY': 'HyDra_Unionagency1.0@prod_server',
        'GATEWAY': 'http://103.71.51.51:5006/api/Orders',
        'QUERY_GATEWAY': 'http://103.71.51.51:5006/api/Orders/Status',
        'INFO': '正式环境',
    },
    'witch': {
        'API_KEY': 'HyDra_Unionagency1.0@prod_server',
        'GATEWAY': 'http://103.71.51.51:5006/api/Orders',
        'QUERY_GATEWAY': 'http://103.71.51.51:5006/api/Orders/Status',
        'INFO': '正式环境',
    },
    'zszs': {
        'API_KEY': 'HyDra_Unionagency1.0@prod_server',
        'GATEWAY': 'http://103.71.51.51:5006/api/Orders',
        'QUERY_GATEWAY': 'http://103.71.51.51:5006/api/Orders/Status',
        'INFO': '正式环境',
    },
    'diablo': {
        'API_KEY': 'HyDra_Unionagency1.0@prod_server',
        'GATEWAY': 'http://103.71.51.51:5006/api/Orders',
        'QUERY_GATEWAY': 'http://103.71.51.51:5006/api/Orders/Status',
        'INFO': '正式环境',
    },
    'dagent': {
        'API_KEY': 'HyDra_Unionagency1.0@prod_server',
        'GATEWAY': 'http://103.71.51.51:5006/api/Orders',
        'QUERY_GATEWAY': 'http://103.71.51.51:5006/api/Orders/Status',
        'INFO': '正式环境',
    },
    'Testing': {
        'API_KEY': 'HyDra_Unionagency1.0@prod_server',
        'GATEWAY': 'http://103.71.51.51:5006/api/Orders',
        'QUERY_GATEWAY': 'http://103.71.51.51:5006/api/Orders/Status',
        'INFO': '正式环境',
    },
}


def _get_api_key(app_id):
    return APP_CONF[app_id]['API_KEY']


def _get_gateway(app_id):
    return APP_CONF[app_id]['GATEWAY']


def _get_query_gateway(app_id):
    return APP_CONF[app_id]['QUERY_GATEWAY']


# Company+CompanyOrderNo+PlayerId+AccountName+AccountNumber+Amount+Bank+ApiKey
def generate_sign(d, key):
    s = d['company'] + d['companyOrderNo'] + d['playerId'] + d['accountName'] + d['accountNumber'] + d['amount'] + d[
        'bank'] + d['receivedAccountNumber'] + d['notifyUrl'] + key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_notify_sign(d, key):
    s = d['orderNo'] + d['companyOrderNo'] + d['amount'] + d['status'] + d['accountNumber'] + d['cardBalance'] + key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_query_sign(d, key):
    s = d['company'] + d['companyOrderNo'] + key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def create_order(order, bankcard):
    try:
        mch = get_account(order.mch_id)
        app_id = mch.name
        d = {
            "company": app_id,
            "companyOrderNo": '_'.join([str(mch.name), str(order.id)]),
            "playerId": str(order.user_id),
            "accountName": order.pay_account_username,
            "accountNumber": order.pay_account_num,
            "amount": str(order.amount),
            "bank": BANK_DCT[bankcard.bank],
            "receivedAccountNumber": bankcard.account_number,
            "notifyUrl": settings.HYDRA_NOTIFY_URL + mch.name,
        }
        d['sign'] = generate_sign(d, _get_api_key(app_id))
        j = json.dumps(d)
        _LOGGER.info('hydra create data: %s', j)
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        response = requests.post(_get_gateway(app_id), headers=headers, data=j, timeout=5)
        _LOGGER.info('hydra create rsp: %s', response.text)
        data = json.loads(response.text)
        third_id = data.get('orderNo', None)
        if third_id and third_id != '':
            order.status = RECHARGE_ORDER_STATUS.THIRD
            order.third_id = str(third_id)
            order.updated_at = datetime.utcnow()
            order.save()
            return True
        else:
            return False
    except Exception as e:
        _LOGGER.info('hydra create order fail: %s' % e)
        return False


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("hydra sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("hydra notify body: %s", request.body)
    data = json.loads(request.body)
    verify_notify_sign(data, api_key)
    pay_id = int(data['companyOrderNo'].split('_')[1])
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('hydra event does not contain pay ID')
    if data['status'] != 'SUCCESS':
        return
    order = recharge_db.add_order_success(pay_id)
    if data.get('accountNumber'):
        bank_db.update_real_balance(data['accountNumber'], data['cardBalance'])
    success, _ = mch_handler.notify_mch(order)
    _LOGGER.info("hydra notify status: %s", success)
    if not success:
        submit_notify_event(order, TIMER_EVENT_TYPE.MCH_NOTIFY)


def query_order(app_id, pay_id):
    d = {
        "company": app_id,
        "companyOrderNo": app_id + '_' + str(pay_id),
    }
    d['sign'] = generate_query_sign(d, _get_api_key(app_id))
    j = json.dumps(d)
    _LOGGER.info('hydra query_order data: %s', j)
    headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
    response = requests.post(_get_query_gateway(app_id), headers=headers, data=j, timeout=5)
    _LOGGER.info('hydra query_order rsp: %s', response.text)
    if response.status_code != 200:
        return
    data = json.loads(response.text)
    if data['status'] != 'SUCCESS':
        return
    order = recharge_db.add_order_success(pay_id)
    success, _ = mch_handler.notify_mch(order)
    _LOGGER.info("hydra notify status: %s", success)
    if not success:
        submit_notify_event(order, TIMER_EVENT_TYPE.MCH_NOTIFY)
